package com.yizhang.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.LogoutConfigurer;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableMethodSecurity // 开启方法级别的权限校验
public class WebSecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(requests -> requests
                 .requestMatchers("/").permitAll()  // 所有人都可以访问首页
                 .anyRequest().authenticated()  // 剩下所有请求都需要认证登录
            )
            .formLogin(form -> form
                 .loginPage("/user/login")  // 自定义登录页面
                 .permitAll()
            )
            .logout(LogoutConfigurer::permitAll);
        return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService(PasswordEncoder passwordEncoder) {
        UserDetails zhangsan =
                User.withUsername("zhangsan")
                        .password(passwordEncoder.encode("123456"))  // 密码必须加密
                        .roles("admin", "developer")
                        .authorities("read", "write")
                        .build();
        UserDetails lisi =
                User.withUsername("lisi")
                        .password(passwordEncoder.encode("123456"))
                        .roles("developer")
                        .authorities("read")
                        .build();
        return new InMemoryUserDetailsManager(zhangsan, lisi);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
